import { Form, Input, Button, Checkbox, message } from 'antd';
import { useNavigate } from 'react-router-dom'
import { debounce } from 'lodash'
import axios from 'axios'

const Demo = () => {
  const navagate = useNavigate()
  // 登录函数 （注意防抖）
  const onFinish = debounce(async (values: any) => {
    const resp = await axios.post('/api/user/login', values)
    const { code, data, mess } = resp.data
    if (code === 200) {
      // message({ type: 'success', message: '登录成功！！！' })
      message.success('登录成功, 欢迎' + values.user, () => {
        navagate({ pathname: '/' })
        localStorage.setItem('token', data.token)
      })
    } else {
      message.error(mess)
    }
  }, 400);

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <Form
      name="basic"
      labelCol={{
        span: 8,
      }}
      wrapperCol={{
        span: 10,
      }}
      initialValues={{
        remember: true,
      }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        label="用户名"
        name="user"
        rules={[
          {
            required: true,
            message: 'Please input your username!',
          },
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="密码"
        name="pwd"
        rules={[
          {
            required: true,
            message: 'Please input your password!',
          },
        ]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item
        wrapperCol={{
          offset: 8,
          span: 16,
        }}
      >
        <Button type="primary" htmlType="submit">
          登录
        </Button>
      </Form.Item>
    </Form>
  );
};

export default Demo